package wxsdkPakage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.qingning.qn.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import utils.BitmapUtils;
import utils.GlideUtils;

public class WXSharePlugin implements MethodChannel.MethodCallHandler {
    public static final String CHANNEL = "com.ahj/wxSharePlugin";
    static MethodChannel channe;
    private Activity activity;
    String appId;

    public WXSharePlugin(Activity activity) {
        appId = activity.getString(R.string.wxAppid);
        this.activity = activity;
    }

    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        WXSharePlugin plugin = new WXSharePlugin(activity12);
        channe.setMethodCallHandler(plugin);
    }


    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        try {
            if (methodCall.method.equals("wxShareProgram")) {
                String path = methodCall.argument("url");
                IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

                //初始化一个 WXTextObject 对象，填写分享的文本内容
                WXTextObject textObj = new WXTextObject();
                textObj.text = path;

                //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = textObj;
                msg.description = path;

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("text");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;
                //调用api接口，发送数据到微信
                api.sendReq(req);


            }else if (methodCall.method.equals("wxShareUrl")) {

                String url = methodCall.argument("url");
                String title = methodCall.argument("title");
                String shareType = methodCall.argument("shareType");
                String description = methodCall.argument("description");
                IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = url;

                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.description = description;
                msg.title = title;
                Bitmap thumbBmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon_ahj_share);
                msg.thumbData =bmpToByteArray(thumbBmp, true);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = shareType.equals("01") ?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;
                //调用api接口，发送数据到微信
                api.sendReq(req);

            }else if (methodCall.method.equals("wxShareSCProgram")){


                String path = methodCall.argument("url");
                String imageUrl = methodCall.argument("imageUrl");
                String goodsName = methodCall.argument("goodsName");
                String sharType = methodCall.argument("sharType");
                String description = methodCall.argument("description");

                if(TextUtils.isEmpty(imageUrl)){
                    IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

                    //初始化一个WXWebpageObject，填写url
                    WXWebpageObject webpage = new WXWebpageObject();
                    webpage.webpageUrl =path;

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                    WXMediaMessage msg = new WXMediaMessage(webpage);
                    msg.title =goodsName;
                    msg.description =description;
                    Bitmap thumbBmp = BitmapFactory.decodeResource(activity.getResources(), R.drawable.icon_sharelogo);


                    msg.thumbData =bmpToByteArray(thumbBmp, true);

//构造一个Req
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = buildTransaction("webpage");
                    req.message =msg;
//                    req.scene = SendMessageToWX.Req.WXSceneSession;
                    req.scene = "0".equals(sharType) ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                    //req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到微信朋友圈
//调用api接口，发送数据到微信
                    api.sendReq(req);

                    return;
                }
                Glide.with(activity).asBitmap().load(imageUrl)

                        .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);

                        //初始化一个WXWebpageObject，填写url
                        WXWebpageObject webpage = new WXWebpageObject();
                        webpage.webpageUrl =path;

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                        WXMediaMessage msg = new WXMediaMessage(webpage);
                        msg.title =goodsName;
                        msg.description =description;
//                        Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);

                        Bitmap thumbBmp =   BitmapUtils.compressByWidth(resource,100);

                        msg.thumbData =bmpToByteArray(thumbBmp, true);

//构造一个Req
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = buildTransaction("webpage");
                        req.message =msg;
//                        req.scene = SendMessageToWX.Req.WXSceneSession;
                        req.scene = "0".equals(sharType) ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
//调用api接口，发送数据到微信
                        api.sendReq(req);
                    }
                });


                //调用api接口，发送数据到微信
//                api.sendReq(req);
            }else if (methodCall.method.equals("wxSharePic")){
                // 凡泰小程序的路径以 finfile:开头
                String imgUrl = methodCall.argument("url");
                String imgUrl1 = methodCall.argument("fileUrl");
                if(imgUrl.startsWith("finfile:")){
                    String appId = methodCall.argument("appId");// 这个appID是Finlip的id
                    imgUrl  = com.finogeeks.lib.applet.client.FinAppClient.INSTANCE.getAppletApiManager().getFinFileAbsolutePath(activity,appId,imgUrl);
                }

                if(!TextUtils.isEmpty(imgUrl1)) {
                    imgUrl = imgUrl1;
                }

                String path =imgUrl ;
                String imageUrl = imgUrl;//methodCall.argument("url");

                String name= methodCall.argument("goodsName");
                String title = name!=null?name:methodCall.argument("title");
                String description = methodCall.argument("description");
                String sharType = methodCall.argument("sharType");

                Glide.with(activity).asBitmap().load(imageUrl)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);
                                WXImageObject imgObj = new WXImageObject(resource);

                                File sampleDir = new File(activity.getExternalFilesDir(null)+ "WXSHARE_IMAGE");
                                if (!sampleDir.exists()) {
                                    sampleDir.mkdirs();
                                }
                                String path = "image_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".png";
                                File file = new File(sampleDir, path);

                                String filePath=file.getAbsolutePath();
                                BitmapUtils.saveBitmap(resource,filePath);

                                if (checkVersionValid(activity) && checkAndroidNotBelowN()) {

//                                    Toast.makeText(activity, "1231313", Toast.LENGTH_SHORT).show();

                                    File file32 = new File(filePath);
                                    String contentPath = getFileUri(activity, file32);

//                                    Toast.makeText(activity, contentPath+"1231313", Toast.LENGTH_SHORT).show();
//                                    String contentPath = WXOpenSDKFileProviderHelper.getFileUri(activity, file32);

                                    imgObj.setImagePath(contentPath);
                                }
                                else {
                                    imgObj.setImagePath(filePath);
                                }

//                                if(TextUtils.isEmpty(imgUrl1)){
//
//                                }else {
//                                    File file32 = new File(imgUrl1);
//                                    String contentPath = getFileUri(activity, file32);
//                                    imgObj.setImagePath(contentPath);
//                                }

                                System.out.println(imgUrl1);
                                imgObj.imagePath = imgUrl1;

                                WXMediaMessage msg = new WXMediaMessage();
                                msg.mediaObject = imgObj;
                                msg.title = title;
                                msg.description = description;

//                                Bitmap thumbBmp =   BitmapUtils.compressByWidth(resource,100);
//
//                                msg.thumbData =bmpToByteArray(thumbBmp, true);
//
//                                msg.setThumbImage(thumbBmp);
//                                thumbBmp.recycle();

                                Bitmap thumbBmp = Bitmap.createScaledBitmap(resource, 120, 120, true);
                                resource.recycle();
                                msg.thumbData = bmpToByteArray(thumbBmp, true);


                                SendMessageToWX.Req req = new SendMessageToWX.Req();
                                req.transaction = String.valueOf(System.currentTimeMillis());
                                req.message = msg;
                                req.transaction = buildTransaction("img");//  transaction字段用

                                req.scene = "0".equals(sharType) ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                                api.sendReq(req);
                            }
                        });




            }else if (methodCall.method.equals("wxShareFile")){
                String path = methodCall.argument("url");
                String imageUrl = methodCall.argument("url");
                String goodsName = methodCall.argument("goodsName");
                String description = methodCall.argument("description");
                String sharType = methodCall.argument("sharType");

                IWXAPI wxapi = WXAPIFactory.createWXAPI(activity, appId);
                WXFileObject imgObj = new WXFileObject();
                File file = new File(path);
                if (!file.exists()){
                    return;
                }
                if (checkVersionValid(activity) && checkAndroidNotBelowN()) {
                    File file32 = new File(path);
                    String contentPath = getFileUri(activity, file32);

                    imgObj.setFilePath(contentPath);
                }else {
                    imgObj.setFilePath(path);
                }

                WXMediaMessage msg = new WXMediaMessage(imgObj);

                msg.title = goodsName;
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                //创建唯一标识
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;

                wxapi.sendReq(req);

            }
        } catch (Exception e) {
            e.printStackTrace();
//            Toast.makeText(activity, ""+e.toString(), Toast.LENGTH_SHORT).show();
            result.success("");
        }
    }

    public String getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            return null;
        }

        Uri contentUri = FileProvider.getUriForFile(context,
                "com.qingning.qn.fileProvider",  // 要与`AndroidManifest.xml`里配置的`authorities`一致，假设你的应用包名为com.example.app
                file);

        // 授权给微信访问路径
        context.grantUriPermission("com.tencent.mm",  // 这里填微信包名
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

        return contentUri.toString();   // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }


    // 判断微信版本是否为7.0.13及以上
    public boolean checkVersionValid(Context context) {
        IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);
        return api.getWXAppSupportAPI() >= 0x27000D00;
    }

    // 判断Android版本是否7.0及以上
    public boolean checkAndroidNotBelowN() {
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N;
    }
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        int i;
        int j;
        if (bmp.getHeight() > bmp.getWidth()) {
            i = bmp.getWidth();
            j = bmp.getWidth();
        } else {
            i = bmp.getHeight();
            j = bmp.getHeight();
        }

        Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
        Canvas localCanvas = new Canvas(localBitmap);

        while (true) {
            localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0,i, j), null);
            if (needRecycle)
                bmp.recycle();
            ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
            localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                    localByteArrayOutputStream);
            localBitmap.recycle();
            byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
            try {
                localByteArrayOutputStream.close();
                return arrayOfByte;
            } catch (Exception e) {
                //F.out(e);
            }
            i = bmp.getHeight();
            j = bmp.getHeight();
        }
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
